import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

import { User } from "./user"
import { UserService } from "./user.service"
import { Task } from './task'
import { TaskService } from './task.service'

@Component({
  selector: "task-table",
  templateUrl: "./task-table.component.html",
  styleUrls: [ "./task-table.component.css" ]
})
export class TaskTableComponent implements OnInit {
  @Input() project_id: string
  @Input() user_id: string
  @Input() date: string

  mine: User
  tasks: Array<Task> = [ ]
  current_task: Array<Task>=[ ]
  constructor(
      private router: Router,
      private userService: UserService,
      private taskService: TaskService,
      private location: Location) { }

  ngOnInit(): void {
    this.userService.getUserMine().then(user => this.mine = user)

    var argv = { project_id: this.project_id, receiver_id: this.user_id,
                date: this.date, contain: "stage,receiver,project,days" }
    if (!this.project_id) delete argv.project_id
    if (!this.user_id) delete argv.receiver_id
    if (!this.date) delete argv.date
    this.taskService.getList(argv).then(tasks => this.setTasks(tasks))
  }

  setTasks(tasks: Array<Task>): void {
    var now = new Date()
    var today = new Date(now.getFullYear() + "-" +
                         (now.getMonth() + 1) + "-" + now.getDate())
    tasks.map(task => {
      task.work_days = 0
      task.used_days = 0
      task.remain_days = 0
      task.days.map(day => {
        if (day.work) {
          task.work_days += 1
          if (new Date(day.date) < today)
            task.used_days += 1
          else
            task.remain_days += 1
        }
      })
    })
    this.tasks = tasks
  }

  goProject(project_id: string): boolean {
    this.router.navigate([ "projects", project_id ])
    return false
  }

  goTask(task: Task): boolean {
    this.router.navigate([ "tasks", task.id ])
    return false
  }

  goUserTasks(user_id): boolean {
    if (!user_id) return false
    this.router.navigate([ "users", user_id, "tasks" ])
    return false
  }

  changeTask(task, field): void {
    this.taskService.update(task, field)
  }
}
